#!/bin/bash

expiredSession=`echo "SELECT COUNT(*) FROM client.sessions WHERE logout IS NULL and timestamp < DATE_SUB(now(), INTERVAL 60 MINUTE);" | mysql -u cron-halter -D client | tail -n1`

if [ $expiredSession -gt 0 ]
then
	echo "Cerrando las sesiones de mas de 1 hora. Muahahaha!!"
	echo "UPDATE sessions SET logout=NOW() WHERE timestamp > DATE_SUB(now(), INTERVAL 5 MINUTE) AND logout IS NULL;" | mysql -u cron-halter -D client | tail -n1
fi

validSession=`echo "SELECT COUNT(*) FROM client.sessions WHERE logout IS NULL AND timestamp > DATE_SUB(now(), INTERVAL 60 MINUTE);" | mysql -u cron-halter -D client | tail -n1`

if [ $validSession -gt 0 ]
then
	echo "Valid sesions.... exiting"
	exit 0
fi

#pendingExperiments=`echo "SELECT COUNT(*) FROM vm.EXPERIMENTS WHERE results IS NULL;" | mysql -u cron-halter -D client | tail -n1`

vmid=`cat /etc/vmid`
ip=`ifconfig | grep addr:1 | awk '{print $2}' | cut -d':' -f2 | head -n1`
#vmmip=`echo ${ip%.*}.254`
 
xml="<remote_call>
           <function_name>logout</function_name>
           <arguments>
                 <vmid>$vmid</vmid>
                 <ip>$ip</ip>
                 <port>0</port>
           </arguments>
         </remote_call>"

echo "Voy a enviar esto: $xml"

# Send halt to socket
exec 3<> /dev/tcp/host-vm/17216
#cat logout4.xml 1>&3
echo $xml 1>&3
echo 1>&3

exit
#mysql -u cron-halter -f -c "UPDATE sessions SET logout=NOW() WHERE logout is null;"
